package org.vpm.mediaplayer;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class PlayerActivity extends Activity {
	private ImageButton mPlayButton, mPauseButton, mBackButton, mForwardButton;
	private SeekBar	mPlaybackBar;
	private TextView mCurrentText, mTotalText;
	private LinearLayout mControlsRow;
	private IPlayerService mPlayerService;
	
	Handler mUpdateHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.arg1) {
				case PlayerService.PREPARED:
					try {
						mPlayerService.startTrack();
						showTrackStatus();
						showPlaying();
					} catch (RemoteException e) {
						Log.e("Media Player", "Remote Exception", e);
					}
					break;
				case PlayerService.UPDATE:
					updateProgress(msg.arg2);
					break;
				case PlayerService.ERROR:
					Log.d("Media Player", String.format("Media Player Error: %d", msg.arg2));
					break;
				case PlayerService.BUFFERING:
					mPlaybackBar.setSecondaryProgress(msg.arg2);
					break;
				case PlayerService.COMPLETION:
					break;
			}
		}
	};
	
	IPlayerServiceCallback mPlayerUpdateCallback = new IPlayerServiceCallback.Stub() {
		@Override
		public void update(int type, int value) throws RemoteException {
			mUpdateHandler.sendMessage(mUpdateHandler.obtainMessage(1, type, value));
		}
	};
	
	ServiceConnection mPlayerConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			try {
				mPlayerService.unregisterCallback(mPlayerUpdateCallback);
			} catch (RemoteException e) {
				Log.e("Media Player", "Remote Exception", e);
			}
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPlayerService = IPlayerService.Stub.asInterface(service);
			try {
				mPlayerService.registerCallback(mPlayerUpdateCallback);
				if(mPlayerService.isActive()) {
					showTrackStatus();
				} else {
					mPlayerService.remoteTrack();
				}
				showPlaying();
			} catch (RemoteException e) {
				Log.e("Media Player", "Remote Exception", e);
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.media_player);
		
		mPlayButton = (ImageButton)findViewById(R.id.play);
		mPlayButton.setOnClickListener(mPlayListener);
		mPauseButton = (ImageButton)findViewById(R.id.pause);
		mPauseButton.setOnClickListener(mPauseListener);
		mBackButton = (ImageButton)findViewById(R.id.rew);
		mForwardButton = (ImageButton)findViewById(R.id.ffwd);
		
		mPlaybackBar = (SeekBar)findViewById(R.id.mediacontroller_progress);
		mCurrentText = (TextView)findViewById(R.id.time_current);
		mTotalText = (TextView)findViewById(R.id.time);
		
		mControlsRow = (LinearLayout)findViewById(R.id.ControlsRow);
		
		startService(new Intent(this, PlayerService.class));
		bindService(new Intent(this, PlayerService.class), mPlayerConnection, BIND_AUTO_CREATE);
	}
	
	public void onRestart() {
		super.onRestart();
		showPlaying();
	}
	
	public void onDestroy() {
		unbindService(mPlayerConnection);
		super.onDestroy();
	}
	
	private SeekBar.OnSeekBarChangeListener PlaybackBarChangedListener = new SeekBar.OnSeekBarChangeListener() {
		private Boolean mPlayingFlag;
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			try {
				if(!mPlayingFlag) {
					mPlayerService.startTrack();
				}
			} catch (RemoteException e) {
				Log.e("Media Player", "Remote Exception", e);
			}
		}
		
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			try {
				if(mPlayerService.isPlaying()) {
					mPlayerService.pauseTrack();
					mPlayingFlag = false;
				} else {
					mPlayingFlag = true;
				}
			} catch (RemoteException e) {
				Log.e("Media Player", "Remote Exception", e);
			}
		}
		
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			try {
				if(fromUser) mPlayerService.seekTrack(progress);
			} catch (RemoteException e) {
				Log.e("Media Player", "Remote Exception", e);
			}
		}
	};
	
	private void showTrackStatus() throws RemoteException {
		int duration = mPlayerService.getDuration();
		int progress = mPlayerService.getCurrentPosition();
		
		mTotalText.setText(buildTime(duration));
		mPlaybackBar.setMax(duration);
		mCurrentText.setText(buildTime(progress));
		mPlaybackBar.setProgress(progress);
		mControlsRow.setVisibility(View.VISIBLE);
	}
	
	private void showPlaying() {
		try {
			if(mPlayerService != null && mPlayerService.isPlaying()) {
				mPlayButton.setVisibility(View.GONE);
				mPauseButton.setVisibility(View.VISIBLE);
			} else {
				mPlayButton.setVisibility(View.VISIBLE);
				mPauseButton.setVisibility(View.GONE);
			}
		} catch (RemoteException e) {
			Log.e("Media Player", "Remote Exception", e);
		}
	}
	
	private OnClickListener mPlayListener = new OnClickListener() {
		public void onClick(View v) {
			startPlayback();
		}
    };

    private OnClickListener mPauseListener = new OnClickListener() {
		public void onClick(View v) {
			pausePlayback();
		}
    };
    
    private void startPlayback() {
		try {
			mPlayerService.startTrack();
			showPlaying();
		} catch (RemoteException e) {
			Log.e("Media Player", "Remote Exception", e);
		}
    }
    private void pausePlayback() {
		try {
			mPlayerService.pauseTrack();
			showPlaying();
		} catch (RemoteException e) {
			Log.e("Media Player", "Remote Exception", e);
		}
    }
    
    private void updateProgress(int progress) {
		mPlaybackBar.setProgress(progress);
		mCurrentText.setText(buildTime(progress));
    }
    
    private String buildTime(int time) {
    	int seconds = time / 1000;
    	int sec = seconds % 60;
    	int minutes = seconds / 60;
    	int min = minutes % 60;
    	int hours = minutes / 60;
    	int hur = hours % 24;
    	
    	return String.format("%d:%02d:%02d", hur, min, sec);
    }
}	
